package com.github.jiangxch.rpc.transport.netty;

import com.github.jiangxch.rpc.serialization.Serializer;
import com.github.jiangxch.rpc.serialization.jdk.JdkSerializer;
import com.github.jiangxch.rpc.transport.Channel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * @author: jiangxch
 * @date: 2021/2/20 16:45
 */
public class NettyChannel implements Channel {
    
    private Serializer serializer;

    private io.netty.channel.Channel channel;

    public NettyChannel(io.netty.channel.Channel channel, Serializer serializer) {
        this.channel = channel;
        this.serializer = serializer;
    }

    @Override
    public InetSocketAddress getRemoteAddress() {
        return (InetSocketAddress) channel.remoteAddress();
    }

    @Override
    public void send(Object message) throws IOException {
        ByteBuf buf = Unpooled.buffer();
        byte[] bytes = serializer.serialize(message);
        buf.writeInt(bytes.length);
        buf.writeBytes(bytes);
        channel.writeAndFlush(buf);
    }

    public static Channel wrap(ChannelHandlerContext ctx,Serializer serializer) {
        return new NettyChannel(ctx.channel(),serializer);
    }
    
    public static Channel wrap(io.netty.channel.Channel channel,Serializer serializer) {
        return new NettyChannel(channel,serializer);
    }
}
